package com.sea.base.ext.global

import android.animation.Animator
import android.graphics.drawable.AnimationDrawable
import android.view.ViewPropertyAnimator
import android.view.animation.Animation

/**
 * 注意：初始化时立即调用无效，需要post
 */
@Deprecated("由于停在最后一帧不稳定，建议把最后一帧放到第一帧的位置")
fun AnimationDrawable.stopToLastFrame() {
    stop()
    selectDrawable(numberOfFrames - 1)
}

inline fun <T : Animation> T.setAnimationListener(
    crossinline onStart: (T.() -> Unit) = {},
    crossinline onRepeat: (T.() -> Unit) = {},
    crossinline onEnd: (T.() -> Unit) = {}
) = object : Animation.AnimationListener {
    override fun onAnimationStart(animation: Animation?) = onStart()
    override fun onAnimationEnd(animation: Animation?) = onEnd()
    override fun onAnimationRepeat(animation: Animation?) = onRepeat()
}.also {
    this.setAnimationListener(it)
}

inline fun ViewPropertyAnimator.setListener(
    crossinline onStart: ViewPropertyAnimator.() -> Unit = {},
    crossinline onRepeat: ViewPropertyAnimator.() -> Unit = {},
    crossinline onCancel: ViewPropertyAnimator.() -> Unit = {},
    crossinline onEnd: ViewPropertyAnimator.() -> Unit = {},
) = object : Animator.AnimatorListener {
    override fun onAnimationRepeat(animator: Animator) = onRepeat()
    override fun onAnimationEnd(animator: Animator) = onEnd()
    override fun onAnimationCancel(animator: Animator) = onCancel()
    override fun onAnimationStart(animator: Animator) = onStart()
}.also {
    this.setListener(it)
}